{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2024 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "R5DkeFMP75as"
      },
      "source": [
        "# Live API - Quickstart"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tqktCVDm1yFo"
      },
      "source": [
        "<table align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/panaversity/learn-agentic-ai/blob/main/12_langchain_ecosystem/langgraph/langgraph_easy_tutorial/00_gemini_2_simple_live_api_helloworld/live_api_starter.ipynb\"><img src=\"https://ai.google.dev/site-assets/images/docs/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iS0rHk3RBrtA"
      },
      "source": [
        "# Google Gen AI SDK (experimental)\n",
        "The new Google Gen AI SDK provides a unified interface to Gemini 2.0 through both the Gemini Developer API and the Gemini API on Vertex AI. With a few exceptions, code that runs on one platform will run on both. This means that you can prototype an application using the Developer API and then migrate the application to Vertex AI without rewriting your code.\n",
        "\n",
        "The Gen AI SDK also supports the Gemini 1.5 models.\n",
        "\n",
        "The new SDK is available in Python and Go, with Java and JavaScript coming soon.\n",
        "\n",
        "You can start using the SDK as shown below.\n",
        "\n",
        "Install the new SDK: pip install google-genai\n",
        "\n",
        "Then import the library, initialize a client, and generate content:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Mfk6YY3G5kqp"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d5027929de8f"
      },
      "source": [
        "### Install SDK\n",
        "\n",
        "The new **[Google Gen AI SDK](https://ai.google.dev/gemini-api/docs/sdks)** provides programmatic access to Gemini 2.0 (and previous models) using both the [Google AI for Developers](https://ai.google.dev/gemini-api/docs) and [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/overview) APIs. With a few exceptions, code that runs on one platform will run on both.\n",
        "\n",
        "More details about this new SDK on the [documentation](https://ai.google.dev/gemini-api/docs/sdks) or in the [Getting started](../gemini-2/get_started.ipynb) notebook."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "46zEFO2a9FFd"
      },
      "outputs": [],
      "source": [
        "!pip install -U -q google-genai"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CTIfnvCn9HvH"
      },
      "source": [
        "### Set up your API key\n",
        "\n",
        "To run the following cell, your API key must be stored in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see [Authentication](../quickstarts/Authentication.ipynb) for an example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {
        "id": "A1pkoyZb9Jm3"
      },
      "outputs": [],
      "source": [
        "from google.colab import userdata\n",
        "import os\n",
        "\n",
        "os.environ['GOOGLE_API_KEY'] = userdata.get('GOOGLE_API_KEY')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GOOZsm7i9io6"
      },
      "source": [
        "### Import\n",
        "\n",
        "Import all the necessary modules."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "id": "Yd1vs3cP8EmS"
      },
      "outputs": [],
      "source": [
        "from google import genai"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3Hx_Gw9i0Yuv"
      },
      "source": [
        "### Initialize SDK client\n",
        "\n",
        "The client will pick up your API key from the environment variable.\n",
        "To use the live API you need to set the client version to `v1alpha`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "metadata": {
        "id": "HghvVpbU0Uap"
      },
      "outputs": [],
      "source": [
        "from google import genai\n",
        "client = genai.Client()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QOov6dpG99rY"
      },
      "source": [
        "### Select a model\n",
        "\n",
        "Multimodal Live API are a new capability introduced with the [Gemini 2.0](https://ai.google.dev/gemini-api/docs/models/gemini-v2) model. It won't work with previous generation models.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "metadata": {
        "id": "27Fikag0xSaB"
      },
      "outputs": [],
      "source": [
        "MODEL: str = \"gemini-2.0-flash-exp\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jj7gDzfDOq4h"
      },
      "source": [
        "## Text to Text\n",
        "\n",
        "The simplest way to use the Live API is as a text-to-text chat interface, but it can do **a lot** more than this."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "dDfslcyIOqgI",
        "outputId": "fcd0a867-14af-4c5f-9815-ccccb6497a24"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Okay, let's break down how AI works, in a way that's hopefully understandable without getting bogged down in technical jargon. We'll focus on the core concepts, and I'll use analogies to help illustrate.\n",
            "\n",
            "**At its Heart: Learning from Data**\n",
            "\n",
            "The primary concept underlying most AI today is that it **learns from data**. It's not programmed with explicit instructions for every possible situation; instead, it's fed massive amounts of data and discovers patterns and relationships within that data. Think of it like learning a new language:\n",
            "\n",
            "*   **Traditional programming:** You'd write explicit grammar rules and vocabulary lists.\n",
            "*   **AI (Machine Learning):** You'd immerse a person in the language, exposing them to vast amounts of text and speech, and they'd eventually grasp the grammar and vocabulary by observing patterns.\n",
            "\n",
            "**Key Components of AI (Machine Learning):**\n",
            "\n",
            "1.  **Data:** This is the fuel that drives AI. It could be anything: images, text, numbers, audio, etc. The quality and quantity of data are crucial for good performance.\n",
            "\n",
            "2.  **Algorithms:** These are the mathematical formulas and processes that the AI uses to learn from the data. Different algorithms are suited for different types of tasks and data. Think of them like different recipes for learning.\n",
            "\n",
            "3.  **Models:** These are the internal representations of the patterns and relationships that the algorithm has learned. They're like the 'understanding' that the AI develops. You could think of a model like a summary of the patterns found in the data. It is now capable of making predictions and decisions based on what was learned.\n",
            "\n",
            "4. **Training:** Training is the process of feeding the data into an algorithm and letting it build a model. The AI algorithm will adjust its internal calculations until it can consistently predict or classify the data correctly. This is like studying the language extensively to gain proficiency. The model is then 'trained'.\n",
            "\n",
            "5. **Inference/Prediction:** Once the model is trained, it can then be used to make predictions or classifications on new, unseen data. This is like using your language skills in a new situation or conversation.\n",
            "\n",
            "**Types of Learning:**\n",
            "\n",
            "*   **Supervised Learning:** Like learning with a teacher. The AI is given labeled data (e.g., pictures of cats *labeled* \"cat\" and pictures of dogs *labeled* \"dog\"). It learns to associate the images with their correct labels.\n",
            "*   **Unsupervised Learning:** Like exploring data on your own. The AI is given unlabeled data and tries to find patterns or structures on its own (e.g., grouping customers based on purchase behavior).\n",
            "*   **Reinforcement Learning:** Like learning through trial and error. The AI takes actions in an environment and receives rewards or penalties based on those actions (e.g., learning to play a game).\n",
            "\n",
            "**Analogy: Learning to Identify Fruit**\n",
            "\n",
            "Let's say you want to build an AI that can identify different kinds of fruit.\n",
            "\n",
            "*   **Data:** You feed it lots of images of apples, bananas, and oranges.\n",
            "*   **Algorithm:** You choose a specific algorithm suitable for image recognition, let's say a type of neural network (explained more below)\n",
            "*   **Training:** The algorithm analyzes the images and tries to learn what makes an apple different from a banana or orange. It adjusts its internal parameters until it can consistently tell them apart.\n",
            "*   **Model:** The model has now captured the characteristics that distinguish different fruits. It now understands that apples are usually red, bananas are yellow and slightly curved etc.\n",
            "*   **Inference:** When you show it a new image of an apple, it will correctly identify it.\n",
            "\n",
            "**The Role of Neural Networks (Deep Learning)**\n",
            "\n",
            "A very prominent technique in AI, especially for complex tasks like image recognition, is **Deep Learning**, which uses **neural networks**.\n",
            "\n",
            "*   **Inspired by the human brain:** Neural networks are structured like the connections of neurons in our brains.\n",
            "*   **Layers of processing:** They have multiple layers, where each layer extracts increasingly complex features from the data.\n",
            "*   **Powerful for pattern recognition:** This layered approach allows them to learn intricate patterns in data, making them very effective for tasks like image, speech, and natural language processing.\n",
            "\n",
            "**A Basic Neural Network Analogy:**\n",
            "Think of a neural network like a series of interconnected sieves.\n",
            "\n",
            "1.  **Input:** You start by pouring raw ingredients (data) into the first sieve.\n",
            "2.  **Layers of Sieves:** Each sieve has different hole sizes and patterns. As the data passes through each sieve, it filters out specific features. The first layer might filter out basic things like edges and corners in an image, the next layer might detect shapes, and then another layer might recognize parts of objects.\n",
            "3.  **Output:** Finally, the data comes out at the end, having been processed by multiple layers, with specific patterns and features extracted. This final output is used to make a prediction or decision.\n",
            "\n",
            "**Limitations of AI:**\n",
            "\n",
            "*   **Data Dependent:** AI models are only as good as the data they are trained on. Biased data will lead to biased AI.\n",
            "*   **Lack of Common Sense:** AI often lacks the real-world understanding and common sense that humans possess.\n",
            "*   **Not Truly \"Thinking\":** AI is not truly conscious or understanding in the way humans are. They are sophisticated pattern-matching tools.\n",
            "*   **\"Black Box\" Problem:** The inner workings of complex AI models (especially neural networks) can be difficult to interpret. This can make it challenging to understand *why* an AI made a particular decision.\n",
            "\n",
            "**In Summary:**\n",
            "\n",
            "AI works by learning from data, using algorithms to identify patterns, and creating models that can make predictions or decisions.  Machine Learning, and in particular Deep Learning using neural networks, are key areas of focus. It's a rapidly evolving field with incredible potential and some important limitations.\n",
            "\n",
            "Hopefully, this explanation is helpful! Let me know if you have any more questions.\n",
            "\n"
          ]
        }
      ],
      "source": [
        "response = client.models.generate_content(\n",
        "    model=MODEL, contents='How does AI work?'\n",
        ")\n",
        "print(response.text)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "Tce3stUlHN0L"
      ],
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
